const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const chalk = require('chalk');
const path = require('path');
const fs = require('fs');

// 基本错误处理，确保即使日志系统有问题也能显示错误
function safeLog(level, message) {
  try {
    console[level === 'error' ? 'error' : 'log'](message);
  } catch (e) {
    // 终极错误处理
  }
}

// 安全创建日志目录
try {
  const logDir = path.join(__dirname, '..', 'logs');
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
    safeLog('log', `日志目录创建成功: ${logDir}`);
  }
} catch (error) {
  safeLog('error', `创建日志目录失败: ${error.message}`);
}

// 定义日志级别颜色
const levelColors = {
  debug: 'blue',
  info: 'green',
  warn: 'yellow',
  error: 'red',
  critical: 'magenta'
};

// 格式化函数 - 控制台输出（带颜色）
const consoleFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
  winston.format.printf((info) => {
    const { timestamp, level, message, ...meta } = info;
    const coloredLevel = chalk[levelColors[level] || 'white'](
      level.toUpperCase().padEnd(8)
    );
    const metaString = Object.keys(meta).length > 0 
      ? ' ' + JSON.stringify(meta, null, 2)
      : '';
    return `${chalk.gray(timestamp)} ${coloredLevel} ${message}${metaString}`;
  })
);

// 格式化函数 - 文件输出
const fileFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
  winston.format.json()
);

// 定义日志目录
const logDir = path.join(__dirname, '..', 'logs');

// 创建日志记录器
const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  levels: {
    debug: 0,
    info: 1,
    warn: 2,
    error: 3,
    critical: 4
  },
  transports: [
    // 控制台输出（简化版）
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
      )
    }),
    
    // 简化的文件日志
    new winston.transports.File({
      filename: path.join(logDir, 'combined.log'),
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
      )
    })
  ]
});

// 添加错误处理
logger.on('error', (error) => {
  safeLog('error', `日志系统错误: ${error.message}`);
});

// 创建带标签的日志方法（添加错误处理）
function createTaggedLogger(tag) {
  return {
    debug: (message, meta) => {
      try {
        logger.debug(`[${tag}] ${message}`, meta || {});
      } catch (error) {
        safeLog('error', `DEBUG [${tag}] ${message} (日志记录失败: ${error.message})`);
      }
    },
    info: (message, meta) => {
      try {
        logger.info(`[${tag}] ${message}`, meta || {});
      } catch (error) {
        safeLog('log', `INFO [${tag}] ${message}`);
      }
    },
    warn: (message, meta) => {
      try {
        logger.warn(`[${tag}] ${message}`, meta || {});
      } catch (error) {
        safeLog('log', `WARN [${tag}] ${message}`);
      }
    },
    error: (message, meta) => {
      try {
        logger.error(`[${tag}] ${message}`, meta || {});
      } catch (error) {
        safeLog('error', `ERROR [${tag}] ${message}`);
      }
    },
    critical: (message, meta) => {
      try {
        logger.error(`[${tag}] CRITICAL: ${message}`, meta || {});
      } catch (error) {
        safeLog('error', `CRITICAL [${tag}] ${message}`);
      }
    }
  };
}

// 导出日志工具
module.exports = {
  logger,
  createTaggedLogger,
  // 工具函数
  setLogLevel: (level) => {
    try {
      logger.level = level;
      logger.info(`Log level set to: ${level}`);
    } catch (error) {
      safeLog('error', `设置日志级别失败: ${error.message}`);
    }
  }
};

// 记录日志系统初始化
setTimeout(() => {
  try {
    logger.info('Winston日志系统初始化完成');
  } catch (error) {
    safeLog('log', 'Winston日志系统初始化完成');
  }
}, 100);